#include "pool_head.h"

int send_message(int local_fd,int new_fd, int flag){
    struct msghdr msg;
    memset(&msg,0,sizeof(msg));
    
    struct iovec vec[1];
    //通过正文信息传送标记位
    vec[0].iov_base = &flag;
    vec[0].iov_len = sizeof(flag);
    msg.msg_iov = vec;
    msg.msg_iovlen = sizeof(vec) / sizeof(vec[0]);

    struct cmsghdr* cms = (struct cmsghdr*)malloc(CMSG_LEN(sizeof(int)));
    cms->cmsg_len = CMSG_LEN(sizeof(int));
    cms->cmsg_level = SOL_SOCKET;
    cms->cmsg_type = SCM_RIGHTS;

    void *p = CMSG_DATA(cms);
    int *q = (int*)p;
    *q = new_fd;

    msg.msg_control = cms;
    msg.msg_controllen = CMSG_LEN(sizeof(int));

    sendmsg(local_fd,&msg,0);

    return 0;
}


int recv_message(int local_fd,int *new_fd, int *flag){

    struct msghdr msg;
    memset(&msg,0,sizeof(msg));

    //开辟一个空间存标记位的值
    int *num = (int*)malloc(sizeof(int));
    struct iovec vec[1];
    //通过正文信息接收标记位
    vec[0].iov_base = num;
    vec[0].iov_len = sizeof(int);

    msg.msg_iov = vec;
    msg.msg_iovlen = sizeof(vec) / sizeof(vec[0]);

    struct cmsghdr* cms = (struct cmsghdr*)malloc(CMSG_LEN(sizeof(int)));
    cms->cmsg_len = CMSG_LEN(sizeof(int));
    cms->cmsg_level = SOL_SOCKET;
    cms->cmsg_type = SCM_RIGHTS;

    msg.msg_control = cms;
    msg.msg_controllen = CMSG_LEN(sizeof(int));

    recvmsg(local_fd,&msg,0);

    void *p = CMSG_DATA(cms);
    int *q = (int*)p;
    *new_fd = *q;
    *flag = *num;
    free(num);
    return 0;

}